package com.bzkj.basicinfo.service.wms.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bzkj.basicinfo.domain.ncc.NccBasicSkuInfo;
import com.bzkj.basicinfo.domain.ncc.NccBasicStoStock;
import com.bzkj.basicinfo.domain.ncc.NccMaterialManufacturer;
import com.bzkj.basicinfo.domain.wms.WmsQaHistoryEntity;
import com.bzkj.basicinfo.domain.wms.WmsStoStockEntity;
import com.bzkj.basicinfo.domain.wms.WmsStoStockLimitationEntity;
import com.bzkj.basicinfo.domain.wms.dto.FreezeDto;
import com.bzkj.basicinfo.domain.wms.dto.WmsStoStockDto;
import com.bzkj.basicinfo.domain.wms.vo.RequestStoStockVo;
import com.bzkj.basicinfo.mapper.*;
import com.bzkj.basicinfo.service.wms.WmsStoStockService;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.domain.R;
import com.bzkj.common.core.domain.entity.SysUser;
import com.bzkj.common.utils.SecurityUtils;
import com.bzkj.common.utils.StringUtils;
import com.bzkj.common.utils.uuid.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author wzc
 * @description 针对表【wms_sto_stock(库存表-批次商品货位)】的数据库操作Service实现
 * @createDate 2025-01-02 09:51:37
 */
@Slf4j
@Service
public class WmsStoStockServiceImpl implements WmsStoStockService {
    @Autowired
    private WmsStoStockMapper wmsStoStockMapper;

    @Autowired
    private WmsStoStockLimitationMapper wmsStoStockLimitationMapper;

    @Autowired
    private TableXXXSkuMapper tableXXXSkuMapper;

    @Autowired
    private WmsQaHistoryMapper wmsQaHistoryMapper;

    @Autowired
    private NccBasicSkuInfoMapper nccBasicSkuInfoMapper;

    @Autowired
    private NccMaterialManufacturerMapper nccMaterialManufacturerMapper;

    @Autowired
    private NccBasicStoStockMapper nccBasicStoStockMapper;

    @Value("${ncc.baseUrl}")
    private String baseUrl;


    /**
     * 设置出库状态
     *
     * @param entity
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public R<WmsStoStockDto> setOutboundLimit(WmsStoStockDto entity) {
        try {
            wmsStoStockMapper.updateStoStock(entity);
            // 添加操作日志
            WmsStoStockEntity one = wmsStoStockMapper.finWmsStoStockOne(entity.getPkMaterial(), entity.getPkBatchcode(), null, null);
            if (!one.getSkuState().equals(entity.getPkStorestate())) {
                WmsQaHistoryEntity temp = new WmsQaHistoryEntity();
                temp.setPkMaterial(entity.getPkMaterial());
                temp.setPkBatchcode(entity.getPkBatchcode());
                String s = UUID.randomUUID().toString().replace("-", "");
                temp.setWmsQaId(s);
                SysUser user = SecurityUtils.getLoginUser().getUser();
                temp.setOperator(user.getUserId().toString());
                temp.setOperatorName(user.getUserName());
                temp.setOperattime(new Date());
                temp.setType("2");
                temp.setOldValue(one.getSkuState());
                temp.setNewValue(entity.getPkStorestate());
                wmsQaHistoryMapper.saveWmsQaHistory(temp);
            }
            return R.ok(entity);
        } catch (RuntimeException e) {
            log.error("更新失败:{}", e);
            return R.fail("库存调整失败");
        }
    }

    /**
     * 远程调用ncc修改状态
     *
     * @param entity
     * @param one
     */
    private void extracted(RequestStoStockVo vo) {


        NccBasicSkuInfo one = nccBasicSkuInfoMapper.getNccBasicSkuINfoOneByPkMarbasclass(vo.getCmaterialoid());

        vo.setCmaterialoid(one.getCode());
        if (StringUtils.isBlank(one.getFrameCode()) || one.getFrameCode().equals("1")) {
            vo.setCproductorid(null);
        }
        if (StringUtils.isEmpty(vo.getCproductorid())) {
            vo.setCproductorid(null);
        }
        String json = JSONObject.toJSONString(vo);

        // 添加请求头
        HttpRequest body = HttpUtil.createPost(baseUrl).header("SourceSystem", "WMS").header("TargetSystem", "NCC").header("ServiceName", "S011010001A").header("Content-Type", "application/json").header("path", "/nccloud/api/ic/onhand/stateAdjust").body(json);
        //库存状态调整
        HttpResponse response = body.execute();
        if (!response.isOk()) throw new RuntimeException("ncc远程请求异常");

        JSONObject object = JSON.parseObject(response.body());
        Boolean success = (Boolean) object.get("success");
        if (!success) {
            throw new RuntimeException("ncc远程请求异常");
        }
    }

    /**
     * 操作日志记录
     *
     * @param entity
     * @param one
     */
    public void extracted(WmsStoStockEntity entity, WmsStoStockEntity one) {
        WmsQaHistoryEntity temp = new WmsQaHistoryEntity();
        temp.setPkMaterial(entity.getPkMaterial());
        temp.setPkBatchcode(entity.getPkBatchcode());
        SysUser user = SecurityUtils.getLoginUser().getUser();
        temp.setOperator(user.getUserId().toString());
        temp.setOperatorName(user.getUserName());
        temp.setOperattime(new Date());
        temp.setCwarehouseId(entity.getCwarehouseId());
        temp.setCproductorId(entity.getCproductorid());
        DateTime parse = null;
        DateTime retestDateParse = null;
        if (StringUtils.isNotBlank(one.getExpDate())) {
            parse = DateUtil.parse(one.getExpDate(), "yyyy-MM-dd HH:mm:ss");
        }
        if (StringUtils.isNotBlank(one.getRetestDate())) {
            retestDateParse = DateUtil.parse(one.getRetestDate(), "yyyy-MM-dd HH:mm:ss");
        }
        String tableName = "table_" + one.getPkMaterial() + "_sku";
        boolean tableExist = tableXXXSkuMapper.isTableExist(tableName);
        //判断复验期是否修改
        boolean flag = Objects.nonNull(entity.getRetestDate())
                && (Objects.isNull(one.getRetestDate()) || !DateUtil.format(retestDateParse, "yyyy-MM-dd HH:mm:ss").equals(entity.getRetestDate()));
        //有效期，复验期修改时同步修改有效期
        if (flag || (Objects.nonNull(entity.getExpDate()) && Objects.nonNull(parse) && !DateUtil.format(parse, "yyyy-MM-dd HH:mm:ss").equals(entity.getExpDate()))) {
            //先去调用ncc，ncc修改成功后再修改wms
            HttpResponse response = requestExpDate(entity.getPkMaterial(), entity.getPkBatchcode(), entity.getExpDate());
            if (!response.isOk()) {
                throw new RuntimeException("调用ncc失败");
            }
            JSONObject object = JSON.parseObject(response.body());
            Boolean success = (Boolean) object.get("success");
            if (success) {
                if (flag) {
                    entity.setExpDate(entity.getRetestDate());
                }
                wmsStoStockMapper.updateOutboundLimit(entity);
                temp.setType("0");
                temp.setOldValue(one.getExpDate());
                temp.setNewValue(entity.getExpDate());
                String s = UUID.randomUUID().toString().replace("-", "");
                temp.setWmsQaId(s);
                wmsQaHistoryMapper.saveWmsQaHistory(temp);
                if (tableExist) {
                    tableXXXSkuMapper.updateRestAndExpByVbatchCode(tableName, one.getVbatchcode(),
                            DateUtil.parse(entity.getExpDate(), "yyyy-MM-dd HH:mm:ss"), DateUtil.parse(entity.getRetestDate(), "yyyy-MM-dd HH:mm:ss"));
                }
            } else {
                throw new RuntimeException("调用ncc失败");
            }
        }
        //复验期
        if (flag) {
            temp.setType("1");
            temp.setOldValue(one.getRetestDate());
            temp.setNewValue(entity.getRetestDate());
            String s = UUID.randomUUID().toString().replace("-", "");
            temp.setWmsQaId(s);
            wmsQaHistoryMapper.saveWmsQaHistory(temp);
            wmsStoStockMapper.updateOutboundLimit(entity);
            if (tableExist) {
                tableXXXSkuMapper.updateRestAndExpByVbatchCode(tableName, one.getVbatchcode(),
                        DateUtil.parse(entity.getExpDate(), "yyyy-MM-dd HH:mm:ss"), DateUtil.parse(entity.getRetestDate(), "yyyy-MM-dd HH:mm:ss"));
            }
        }
        //库存状态
        if (Objects.nonNull(entity.getSkuState()) && !one.getSkuState().equals(entity.getSkuState())) {
            temp.setType("2");
            temp.setOldValue(one.getSkuState());
            temp.setNewValue(entity.getSkuState());
            String s = UUID.randomUUID().toString().replace("-", "");
            temp.setWmsQaId(s);
            wmsQaHistoryMapper.saveWmsQaHistory(temp);
        }
        //移位
        if (Objects.nonNull(entity.getStoUnitId()) && !one.getStoUnitId().equals(entity.getStoUnitId())) {
            temp.setType("3");
            temp.setOldValue(one.getStoUnitId());
            temp.setNewValue(entity.getStoUnitId());
            String s = UUID.randomUUID().toString().replace("-", "");
            temp.setWmsQaId(s);
            wmsQaHistoryMapper.saveWmsQaHistory(temp);
        }
    }

    /**
     * 更新出库信息
     *
     * @param entity
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateOutboundLimit(WmsStoStockEntity entity) {
        try {
            entity.setQc_user(SecurityUtils.getLoginUser().getUser().getUserName());
            entity.setQc_datetime(new Date());

            WmsStoStockEntity one = wmsStoStockMapper.finWmsStoStockOne(entity.getPkMaterial(), entity.getPkBatchcode(), entity.getCwarehouseId(), entity.getCproductorid());

            extracted(entity, one);
//            wmsStoStockMapper.updateOutboundLimit(entity);
            return AjaxResult.success();
        } catch (Exception e) {
            log.error("更新失败:{}", e);
            if (e.getMessage().equals("SocketTimeoutException: connect timed out") || e.getMessage().equals("调用ncc失败")) {
                return AjaxResult.error("wms调用ncc接口异常，更新失败");
            } else {
                return AjaxResult.error("更新失败");
            }
        }
    }

    /**
     * 冻结操作
     *
     * @param dto
     * @return
     */
    @Override
    public AjaxResult freeze(FreezeDto dto) {
        String pkMaterial = dto.getPkMaterial();
        String tableName = "table_" + pkMaterial + "_sku";
        String pkBatchcode = dto.getPkBatchcode();
        dto.setQc_user(SecurityUtils.getLoginUser().getUser().getUserName());
        dto.setQc_datetime(new Date());
        //操作记录
        WmsQaHistoryEntity historyEntity = new WmsQaHistoryEntity();
        historyEntity.setPkMaterial(pkMaterial);
        historyEntity.setPkBatchcode(pkBatchcode);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        historyEntity.setOperator(user.getUserId().toString());
        historyEntity.setOperatorName(user.getUserName());
        historyEntity.setOperattime(new Date());
        historyEntity.setCwarehouseId(dto.getCwarehouseId());
        historyEntity.setCproductorId(dto.getCproductorid());
        historyEntity.setType("4");
        // 把所有的限制关闭
//        wmsStoStockLimitationMapper.updateStoStockLimitation1(dto);
        if (tableXXXSkuMapper.isTableExist(tableName))
            tableXXXSkuMapper.updateXXXSkuMapperAll(tableName, pkBatchcode, 0);

        WmsStoStockLimitationEntity temp = new WmsStoStockLimitationEntity();
        BeanUtils.copyProperties(dto, temp);
        //根据物料主键批号获取物料信息
        WmsStoStockEntity stoStock = wmsStoStockMapper.finWmsStoStockOne(pkMaterial, dto.getPkBatchcode(), dto.getCwarehouseId(), dto.getCproductorid());
        //冻结状态为0的时候进行取消冻结
        if (dto.getFreezeStatus().equals(0)) {
            dto.setLimitQuantity(0);
            wmsStoStockMapper.updateStoStock1(dto);
            freezeNumToStock(dto, pkMaterial, stoStock);
            historyEntity.setSonType("2");//解冻状态
            String s = UUID.randomUUID().toString().replace("-", "");
            historyEntity.setWmsQaId(s);
            wmsQaHistoryMapper.saveWmsQaHistory(historyEntity);
            return AjaxResult.success("取消冻结成功");
        }

        if (dto.getTypeRestriction().equals(2)) { // 类型限制
            //先解冻数量冻结数据
            freezeNumToStock(dto, pkMaterial, stoStock);
            dto.setLimitQuantity(0);
            wmsStoStockMapper.updateStoStock1(dto);
            String stateCode = dto.getStateCode();//库存状态主键
            //已经冻结数量
            //根据库存状态修改库存表里的数量
            if (stateCode.equals("1001A110000000002T09")) {
                //合格数量
                temp.setBillStatusPk(stateCode);
            }
            if (stateCode.equals("1001ZZ1000000002XCX4")) {
                //不合格数量
                temp.setBillStatusPk(stateCode);
            }
            if (stateCode.equals("1001A110000000002T08")) {
                //待验
                temp.setBillStatusPk(stateCode);
            }
            if (stateCode.equals("1001B1100000008N4LKD")) {
                //限制合格
                temp.setBillStatusPk(stateCode);
            }
            if (stateCode.equals("1001B110000000FNCCLS")) {//研究用  生产环境pk:1001B110000000FNCCLS
                //研究用
                temp.setBillStatusPk(stateCode);
            }
            if (stateCode.equals("1001B1100000008HXPEP")) {
                //待处理
                temp.setBillStatusPk(stateCode);
            }
            if (stateCode.equals("1001B110000000CMZGQ2")) {//合格不予上市  生产环境pk:1001B110000000CMZGQ2
                //合格不予上市
                temp.setBillStatusPk(stateCode);
            }
            if (StringUtils.isBlank(stateCode)) {
                //空状态
                temp.setBillStatusPk("");
            }
            // 设置限制类型
            dto.getTypeMapId().stream().forEach(item -> {
                temp.setTypeMapId(item);
                temp.setLimitQuantity(0);
                temp.setCwarehouseId(dto.getCwarehouseId());
                temp.setProductName(dto.getCproductorid());
                wmsStoStockLimitationMapper.saveStoStockLimitation(temp);
            });
            historyEntity.setSonType("1");//冻结状态
            String s = UUID.randomUUID().toString().replace("-", "");
            historyEntity.setWmsQaId(s);
            wmsQaHistoryMapper.saveWmsQaHistory(historyEntity);
        } else if (dto.getTypeRestriction().equals(3)) { // 追溯码限制
            temp.setLimitQuantity(0);
            temp.setTypeMapId(null);
            dto.setLimitQuantity(0);
            wmsStoStockLimitationMapper.saveStoStockLimitation(temp);
            if (tableXXXSkuMapper.isTableExist(tableName)) {
                dto.getSkuBarId().forEach(item -> tableXXXSkuMapper.updateXXXSkuMapper(item, 9, tableName));
            }
            wmsStoStockMapper.updateStoStock1(dto);
        } else if (dto.getTypeRestriction().equals(1)) { // 数量限制
            //先解冻类型限制的数据
            List<HashMap<String, Object>> list = wmsStoStockLimitationMapper.selectAllListByType(2, pkMaterial, pkBatchcode);
            if (CollectionUtil.isNotEmpty(list)) {
                List<String> stringList = new ArrayList<>();
                list.forEach(i -> {
                    String id = i.get("id").toString();
                    if (StringUtils.isNotBlank(id)) {
                        stringList.add(id);
                    }
                });
                //删除掉类型冻结的数据
                if (CollectionUtils.isNotEmpty(stringList)) {
                    wmsStoStockLimitationMapper.deleteByIds(stringList);
                }
            }
            String stateCode = dto.getStateCode();//库存状态主键
            temp.setTypeMapId(null);
            Integer limitQuantity = dto.getLimitQuantity();//冻结数量
            temp.setLimitQuantity(limitQuantity);
            temp.setBillStatusPk(stateCode);
            //增加冻结数量
            long freezeNum = stoStock.getFreezeNum() + limitQuantity;
            dto.setLimitQuantity(Integer.valueOf(String.valueOf(freezeNum)));
            //删除限制表中的数据
            wmsStoStockLimitationMapper.deleteByPk(pkMaterial, pkBatchcode, stateCode);
            //更新冻结数量
            wmsStoStockMapper.updateStoStock1(dto);
            wmsStoStockLimitationMapper.saveStoStockLimitation(temp);
            historyEntity.setSonType("1");//冻结状态
            String s = UUID.randomUUID().toString().replace("-", "");
            historyEntity.setWmsQaId(s);
            wmsQaHistoryMapper.saveWmsQaHistory(historyEntity);
        }
        return AjaxResult.success("冻结成功");
    }

    /**
     * 数量冻结解冻回填数据
     *
     * @param dto
     * @param pkMaterial
     * @param stoStock
     */
    private void freezeNumToStock(FreezeDto dto, String pkMaterial, WmsStoStockEntity stoStock) {
        //根据批号 物料主键、库存状态主键查询冻结数据
        List<HashMap<String, Object>> billStatus = wmsStoStockLimitationMapper.selectAllListByType(1, pkMaterial, dto.getPkBatchcode());
        //根据库存状态修改库存表里的数量
        billStatus.forEach(item -> {
            String billStatusPk = (String) item.get("bill_status_pk");
            Integer limitQuantity = (Integer) item.get("limit_quantity");
            if (billStatusPk.equals("1001A110000000002T09")) {
//                //合格数量
//                int num = stoStock.getQualifiedNum() + limitQuantity;
//                stoStock.setQualifiedNum(num);
            }
            if (billStatusPk.equals("1001ZZ1000000002XCX4")) {
//                //不合格数量
//                int num = stoStock.getUnqualifiedNum() + limitQuantity;
//                stoStock.setUnqualifiedNum(num);
            }
            if (billStatusPk.equals("1001A110000000002T08")) {
//                //待验
//                int num = stoStock.getQuarantineNum() + limitQuantity;
//                stoStock.setQuarantineNum(num);
            }
            if (billStatusPk.equals("1001B1100000008N4LKD")) {
//                //限制合格
//                int num = stoStock.getLimitEligibilityNum() + limitQuantity;
//                stoStock.setLimitEligibilityNum(num);
            }
            if (billStatusPk.equals("1001B110000000FNCCLS")) {//研究用  生产环境pk:1001B110000000FNCCLS
//                //研究用
//                int num = stoStock.getResearchNum() + limitQuantity;
//                stoStock.setResearchNum(num);
            }
            if (billStatusPk.equals("1001B1100000008HXPEP")) {
//                //待处理
//                int num = stoStock.getPendingNum() + limitQuantity;
//                stoStock.setPendingNum(num);
            }
            if (billStatusPk.equals("1001B110000000CMZGQ2")) {//合格不予上市  生产环境pk:1001B110000000CMZGQ2
//                //合格不予上市
//                int num = stoStock.getQualifiedNoUseNum() + limitQuantity;
//                stoStock.setQualifiedNoUseNum(num);
            }
            if (StringUtils.isBlank(billStatusPk)) {
//                //空状态
//                int num = stoStock.getSkuNoStateNum() + limitQuantity;
//                stoStock.setSkuNoStateNum(num);
            }

            stoStock.setFreezeNum(0L);
            wmsStoStockMapper.update(stoStock);
        });
        //根据物料主键、批号、库存状态删除数量冻结的数据
        wmsStoStockLimitationMapper.deleteByPk(pkMaterial, dto.getPkBatchcode(), null);
    }

    @Autowired
    private WmsStoStockStateMapper wmsStoStockStateMapper;

    /**
     * 状态修改
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public R updateState(RequestStoStockVo vo) {
        WmsStoStockEntity one = wmsStoStockMapper.finWmsStoStockVBatchCodeOne(vo);
        if (Objects.isNull(one)) {
            return R.fail("修改失败，系统中未找到该商品");
        }
        WmsStoStockEntity entity = new WmsStoStockEntity();
        entity.setPkMaterial(one.getPkMaterial());
        entity.setPkBatchcode(one.getPkBatchcode());
        entity.setSkuState(vo.getCadjuststateid());
        entity.setCwarehouseId(vo.getCwarehouseid());
        entity.setCproductorid(vo.getCproductorid());
        entity.setStoUnitId(one.getStoUnitId());
        entity.setExpDate(null);
        entity.setRetestDate(null);
        one.setSkuState(vo.getCstateid());
        //查询生产厂商code
        String cproductorId;
        if (StringUtils.isNotBlank(vo.getCproductorid())) {
            cproductorId = vo.getCproductorid();
        } else {
            cproductorId = StringUtils.isNotBlank(one.getCproductorid()) ? one.getCproductorid() : null;
        }
        if (StringUtils.isNotBlank(cproductorId)) {
            entity.setCproductorid(cproductorId);
            NccMaterialManufacturer manufacturer = nccMaterialManufacturerMapper.queryNccMaterialManufacturerByPkDefDoc(cproductorId);
            if (Objects.nonNull(manufacturer)) {
                vo.setCproductorid(manufacturer.getCode());
            }
        }
        //查询库房id
        String cwarehouseId;
        if (StringUtils.isNotBlank(vo.getCwarehouseid())) {
            cwarehouseId = vo.getCwarehouseid();
        } else {
            cwarehouseId = StringUtils.isNotBlank(one.getCwarehouseId()) ? one.getCwarehouseId() : null;
        }
        if (StringUtils.isNotBlank(cwarehouseId)) {
            entity.setCwarehouseId(cwarehouseId);
            NccBasicStoStock stoStock = nccBasicStoStockMapper.queryNccBasicStoStockByPk(cwarehouseId);
            if (Objects.nonNull(stoStock)) {
                vo.setCwarehouseid(stoStock.getCode());
            }
        }
        //操作日志记录
        extracted(entity, one);
        //调用ncc修改状态
        extracted(vo);
        // 修改前状态
        if (vo.getCstateid().equals("1001ZZ1000000002XCX4")) { // 不合格
            BigDecimal num = one.getUnqualifiedNum().subtract(new BigDecimal(vo.getNadjustnum()));
            one.setUnqualifiedNum(num);
        } else if (vo.getCstateid().equals("1001A110000000002T08")) { // 待验
            BigDecimal num = one.getQuarantineNum().subtract(new BigDecimal(vo.getNadjustnum()));
            one.setQuarantineNum(num);
        } else if (vo.getCstateid().equals("1001A110000000002T09")) { // 合格
            BigDecimal num = one.getQualifiedNum().subtract(new BigDecimal(vo.getNadjustnum()));
            one.setQualifiedNum(num);
        } else if (vo.getCstateid().equals("1001B1100000008N4LKD")) { // 限制合格
            BigDecimal num = one.getLimitEligibilityNum().subtract(new BigDecimal(vo.getNadjustnum()));
            one.setLimitEligibilityNum(num);
        } else if (vo.getCstateid().equals("1001B110000000FNCCLS")) {//研究用 生产环境pk:1001B110000000FNCCLS
            BigDecimal num = one.getResearchNum().subtract(new BigDecimal(vo.getNadjustnum()));
            one.setResearchNum(num);
        } else if (vo.getCstateid().equals("1001B1100000008HXPEP")) {//待处理
            BigDecimal num = one.getPendingNum().subtract(new BigDecimal(vo.getNadjustnum()));
            one.setPendingNum(num);
        } else if (vo.getCstateid().equals("1001B110000000CMZGQ2")) {//合格不予上市  生产环境pk:1001B110000000CMZGQ2
            BigDecimal num = one.getQualifiedNoUseNum().subtract(new BigDecimal(vo.getNadjustnum()));
            one.setQualifiedNoUseNum(num);
        } else if (StringUtils.isBlank(vo.getCstateid())) {//空状态
            BigDecimal num = one.getSkuNoStateNum().subtract(new BigDecimal(vo.getNadjustnum()));
            one.setSkuNoStateNum(num);
        }
        //修改后的状态
        if (vo.getCadjuststateid().equals("1001ZZ1000000002XCX4")) { // 不合格
            BigDecimal num = one.getUnqualifiedNum().add(new BigDecimal(vo.getNadjustnum()));
            one.setUnqualifiedNum(num);
        } else if (vo.getCadjuststateid().equals("1001A110000000002T08")) { // 待验
            BigDecimal num = one.getQuarantineNum().add(new BigDecimal(vo.getNadjustnum()));
            one.setQuarantineNum(num);
        } else if (vo.getCadjuststateid().equals("1001A110000000002T09")) { // 合格
            BigDecimal num = one.getQualifiedNum().add(new BigDecimal(vo.getNadjustnum()));
            one.setQualifiedNum(num);
        } else if (vo.getCadjuststateid().equals("1001B1100000008N4LKD")) { // 限制合格
            BigDecimal num = one.getLimitEligibilityNum().add(new BigDecimal(vo.getNadjustnum()));
            one.setLimitEligibilityNum(num);
        } else if (vo.getCadjuststateid().equals("1001B110000000FNCCLS")) {//研究用  生产环境pk:1001B110000000FNCCLS
            BigDecimal num = one.getResearchNum().add(new BigDecimal(vo.getNadjustnum()));
            one.setResearchNum(num);
        } else if (vo.getCadjuststateid().equals("1001B1100000008HXPEP")) {//待处理
            BigDecimal num = one.getPendingNum().add(new BigDecimal(vo.getNadjustnum()));
            one.setPendingNum(num);
        } else if (vo.getCadjuststateid().equals("1001B110000000CMZGQ2")) {//合格不予上市  生产环境pk:1001B110000000CMZGQ2
            BigDecimal num = one.getQualifiedNoUseNum().add(new BigDecimal(vo.getNadjustnum()));
            one.setQualifiedNoUseNum(num);
        } else if (StringUtils.isBlank(vo.getCadjuststateid())) {//空状态
            BigDecimal num = one.getSkuNoStateNum().add(new BigDecimal(vo.getNadjustnum()));
            one.setSkuNoStateNum(num);
        }
        one.setSkuState("1");
        wmsStoStockMapper.update(one);
        if (vo.getUpdateType() == 1) {
            String tableName = "";
            String vbillcode = wmsStoStockMapper.selectVbillcode(vo.getPkMaterial(), vo.getVbatchcode(), vo.getCgeneralbid());
            if (vbillcode.startsWith("CR")) {
                tableName = "wms_warehouse_in_detail_material";
            } else if (vbillcode.startsWith("TR")) {
                tableName = "wms_warehouse_in_detail_other";
            }
            vo.setVbillcode(vbillcode);
            int i = wmsStoStockMapper.updateQmsState(tableName, vo);
        }
        return R.ok("状态修改成功");
    }

    /**
     * 获取库存状态信息
     *
     * @param vo
     * @return
     */
    @Override
    public R getStoStateInfo(RequestStoStockVo vo) {
        HashMap<String, Object> map = new HashMap<>();

//        WmsStoStockStateEntity one = wmsStoStockStateMapper.findIsExtis(vo);
        WmsStoStockEntity one = wmsStoStockMapper.finWmsStoStockVBatchCodeOne(vo);

        // 如果没有状态信息，则新增一条状态信息
        /**数据放入一张表，废弃wms_sto_stock_state表
         if(Objects.isNull(one)) {
         WmsStoStockStateEntity entity = new WmsStoStockStateEntity();
         entity.setStockId(one1.getId().longValue());
         if(one1.getSkuState().equals("1001ZZ1000000002XCX4")) { // 不合格
         entity.setUnqualifiedNum(one1.getSkuNum().intValue());
         } else if(one1.getSkuState().equals("1001A110000000002T08")) { // 待验
         entity.setQuarantineNum(one1.getSkuNum().intValue());
         } else if(one1.getSkuState().equals("1001A110000000002T09")) { // 合格
         entity.setQualifiedNum(one1.getSkuNum().intValue());
         } else if(one1.getSkuState().equals("1001B1100000008N4LKD")) { // 限制合格
         entity.setLimitEligibilityNum(one1.getSkuNum().intValue());
         }
         // 新增对应状态信息
         wmsStoStockStateMapper.save(entity);
         // 获取最新数据
         one = wmsStoStockStateMapper.findIsExtis(vo);
         }
         */
        if (Objects.nonNull(one)) {
            extracted(one, map);
        }

        return R.ok(map);
    }

    /**
     * 数据拼装
     *
     * @param one
     * @param map
     */
    private static void extracted(WmsStoStockEntity one, HashMap<String, Object> map) {
        HashMap<Object, Object> type1 = new HashMap<>();

        HashMap<Object, Object> map1 = new HashMap<>();
        map1.put("PK_STORESTATE", "1001ZZ1000000002XCX4");
        map1.put("name", "不合格");
        map1.put("unqualified_num", one.getUnqualifiedNum());

        type1.put("key1", map1);

        HashMap<Object, Object> map2 = new HashMap<>();
        map2.put("PK_STORESTATE", "1001A110000000002T08");
        map2.put("name", "待检");
        map2.put("quarantine_num", one.getQuarantineNum());

        type1.put("key2", map2);

        HashMap<Object, Object> map3 = new HashMap<>();
        map3.put("PK_STORESTATE", "1001A110000000002T09");
        map3.put("name", "合格");
        map3.put("qualified_num", one.getQualifiedNum());

        type1.put("key3", map3);

        HashMap<Object, Object> map4 = new HashMap<>();
        map4.put("PK_STORESTATE", "1001B1100000008N4LKD");
        map4.put("name", "限制合格");
        map4.put("limit_eligibility_num", one.getLimitEligibilityNum());

        type1.put("key4", map4);

        HashMap<Object, Object> map5 = new HashMap<>();
        map5.put("PK_STORESTATE", "1001B110000000FNCCLS");//研究用  生产环境pk:1001B110000000FNCCLS
        map5.put("name", "研究用");
        map5.put("research_num", one.getResearchNum());

        type1.put("key5", map5);

        HashMap<Object, Object> map6 = new HashMap<>();
        map6.put("PK_STORESTATE", "1001B110000000CMZGQ2");//合格不予上市  生产环境pk:1001B110000000CMZGQ2
        map6.put("name", "合格不予上市");
        map6.put("qualified_no_use_num", one.getQualifiedNoUseNum());

        type1.put("key6", map6);

        HashMap<Object, Object> map7 = new HashMap<>();
        map7.put("PK_STORESTATE", "1001B1100000008HXPEP");
        map7.put("name", "待处理");
        map7.put("pending_num", one.getPendingNum());

        type1.put("key7", map7);

        if (one.getPendingNum().compareTo(BigDecimal.ZERO) == 0 && one.getQualifiedNum().compareTo(BigDecimal.ZERO) == 0 && one.getQuarantineNum().compareTo(BigDecimal.ZERO) == 0 && one.getQualifiedNoUseNum().compareTo(BigDecimal.ZERO) == 0
                && one.getUnqualifiedNum().compareTo(BigDecimal.ZERO) == 0 && one.getResearchNum().compareTo(BigDecimal.ZERO) == 0 && one.getLimitEligibilityNum().compareTo(BigDecimal.ZERO) == 0) {
            HashMap<Object, Object> map8 = new HashMap<>();
            map8.put("PK_STORESTATE", "");
            map8.put("name", "无库存状态");
            map8.put("sku_no_state_num", one.getSkuNoStateNum());
            type1.put("key8", map8);
        }

        map.put("type1", type1);

        HashMap<Object, Object> type2 = new HashMap<>();

        HashMap<Object, Object> m1 = new HashMap<>();
        m1.put("PK_STORESTATE", "1001ZZ1000000002XCX4");
        m1.put("name", "不合格");
        type2.put("m1", m1);

        HashMap<Object, Object> m2 = new HashMap<>();
        m2.put("PK_STORESTATE", "1001A110000000002T08");
        m2.put("name", "待检");
        type2.put("m2", m2);

        HashMap<Object, Object> m3 = new HashMap<>();
        m3.put("PK_STORESTATE", "1001A110000000002T09");
        m3.put("name", "合格");
        type2.put("m3", m3);

        HashMap<Object, Object> m4 = new HashMap<>();
        m4.put("PK_STORESTATE", "1001B1100000008N4LKD");
        m4.put("name", "限制合格");
        type2.put("m4", m4);


        HashMap<Object, Object> m5 = new HashMap<>();
        m5.put("PK_STORESTATE", "1001B110000000FNCCLS");//研究用  生产环境pk:1001B110000000FNCCLS
        m5.put("name", "研究用");
        m5.put("research_num", one.getResearchNum());

        type2.put("m5", m5);

        HashMap<Object, Object> m6 = new HashMap<>();
        m6.put("PK_STORESTATE", "1001B110000000CMZGQ2");//合格不予上市  生产环境pk:1001B110000000CMZGQ2
        m6.put("name", "合格不予上市");
        m6.put("qualified_no_use_num", one.getQualifiedNoUseNum());

        type2.put("m6", m6);

        HashMap<Object, Object> m7 = new HashMap<>();
        m7.put("PK_STORESTATE", "1001B1100000008HXPEP");
        m7.put("name", "待处理");
        m7.put("pending_num", one.getPendingNum());

        type2.put("m7", m7);

        if (one.getPendingNum().compareTo(BigDecimal.ZERO) == 0 && one.getQualifiedNum().compareTo(BigDecimal.ZERO) == 0
                && one.getQuarantineNum().compareTo(BigDecimal.ZERO) == 0 && one.getQualifiedNoUseNum().compareTo(BigDecimal.ZERO) == 0
                && one.getUnqualifiedNum().compareTo(BigDecimal.ZERO) == 0 && one.getResearchNum().compareTo(BigDecimal.ZERO) == 0 && one.getLimitEligibilityNum().compareTo(BigDecimal.ZERO) == 0) {
            HashMap<Object, Object> m8 = new HashMap<>();
            m8.put("PK_STORESTATE", "");
            m8.put("name", "无库存状态");
            m8.put("sku_no_state_num", one.getSkuNoStateNum());
            type2.put("m8", m8);
        }

        map.put("type2", type2);

    }

    /**
     * 请求失效日期调整
     *
     * @return
     */
    private HttpResponse requestExpDate(String pkMaterial, String pkBatchcode, String expDate) {
        //日期格式处理，ncc接收日期格式为年月日格式
        String date = DateUtil.format(DateUtil.parse(expDate), "yyyy-MM-dd");
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("cmaterialid", pkMaterial);
        jsonMap.put("dvalidate", date);
        jsonMap.put("pk_batchcode", pkBatchcode);

        String json = JSON.toJSONString(jsonMap);

        // 添加请求头并设置连接超时时间
        HttpResponse response = HttpUtil.createPost(baseUrl).setConnectionTimeout(1000).header("SourceSystem", "WMS")
                .header("TargetSystem", "NCC")
                .header("ServiceName", "S011010001A")
                .header("Content-Type", "application/json")
                .header("path", "/nccloud/api/uapbd/scmbatchcode/updatedvalidate")
                .body(json).execute();
        return response;
    }

    //====================批发版本库存相关接口=========================

    @Override
    public AjaxResult queryAllStoStock(WmsStoStockDto dto) {
        return AjaxResult.success(wmsStoStockMapper.selectAllStoStock(dto));
    }

    @Override
    public AjaxResult add(WmsStoStockDto dto) {
        int i = wmsStoStockMapper.insertStoStock(dto);
        if (i > 0) {
            return AjaxResult.success("新增成功");
        } else {
            return AjaxResult.error("新增失败");
        }
    }

    @Override
    public AjaxResult update(WmsStoStockDto dto) {
        int i = wmsStoStockMapper.updatePFStoStock(dto);
        if (i > 0) {
            return AjaxResult.success("修改成功");
        } else {
            return AjaxResult.error("修改失败");
        }
    }

    @Override
    public AjaxResult updateEnableState(String state, String id) {
        int i = wmsStoStockMapper.updateEnableStateById(state,id);
        if (i > 0) {
            return AjaxResult.success("修改成功");
        } else {
            return AjaxResult.error("修改失败");
        }
    }

    @Override
    public AjaxResult deleteById(String id) {
        int i = wmsStoStockMapper.deleteById(id);
        if (i > 0) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除失败");
        }
    }
}